package com.qymerge.manage.core.third.wechat.service.twocode;

import com.qymerge.manage.core.third.wechat.config.WechatCommonConfig;
import com.qymerge.manage.core.third.wechat.dto.twocode.TwoCodeRequestDTO;
import com.qymerge.manage.core.third.wechat.dto.twocode.TwoCodeResponseDTO;
import com.qymerge.manage.core.utils.GsonUtil;
import com.qymerge.manage.core.utils.HttpRequestUtil;
import com.google.gson.reflect.TypeToken;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;

/**
 * Desc 生成带参数的二维码
 * User licong
 * Date 2016/6/20
 * Time 11:38
 */
public class TwoCodeService {

    /**
     * 创建二维码ticket
     *
     * @param accessToken
     * @param requestDto
     * @return
     */
    public static TwoCodeResponseDTO create2CdoeTicket(String accessToken, TwoCodeRequestDTO requestDto) {
        String url = MessageFormat.format(WechatCommonConfig.url_create_2code_ticket, accessToken);
        String result = HttpRequestUtil.requestPostBody(url, requestDto.requestJson());
        TwoCodeResponseDTO responseDto = GsonUtil.json2T(result, new TypeToken<TwoCodeResponseDTO>() {
        }.getType());
        return responseDto;
    }

    /**
     * 通过ticket换取二维码
     *
     * @param ticket
     * @return
     */
    public static String showTwocode(String ticket) {
        String url = "";
        try {
            String encode = URLEncoder.encode(ticket, "utf-8");
            url = MessageFormat.format(WechatCommonConfig.url_show_qrcode, encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("[通过ticket换取二维码] 带参二维码地址：" + url);
        return url;
    }
}
